import { goodsApi } from 'api/goods';
import md5 from '@/utils/md5';

const xcxArg = {
    APP_ID: 'xrHXph2X',
    APP_VALUE: 'XmjUXxVX',
}
/*
*  小程序接口添加官网验证（加密、时间戳、appid）
*/ 
const addToken = ()=>{
    var checkTime = Date.now();
    var diffTime = new Date().getTimezoneOffset();
    checkTime = checkTime + diffTime * 60 * 1000 + 480 * 60 * 1000;
    
    var url = '', checkToken = '';
    checkToken = checkToken.concat(checkTime, '|', xcxArg.APP_VALUE);
    url = url.concat(md5.hexMD5(checkToken), '/', checkTime, '/', xcxArg.APP_ID);
    return url;
}

/**
 * 生成分享出去的小程序二维码（二维码个数不限制）
 * params.path：路径，最前面不带/
 * params.share：参数
 * res.pic：返回的图片
 */
const getWechatCode = (path,params) =>{
    return new Promise((resolve,reject)=>{
        if (path.charAt(0) === '/') {
            path = path.slice(1);
        }
        goodsApi.getWechatCode({
            path: encodeURIComponent(path),
            share: encodeURIComponent(params)
        }).then((res) => {
            resolve(res);
        }).catch(err=>{
            reject(err);
        })
    })  
}
/**
 * 是否为手机号
 */
const isPhoneNumber = val => {
    let reg = /^1[3456789]\d{9}$/
    return reg.test(val)
}
//过万处理(点赞数、浏览量等)
const millionNum = (value)=>{
    let num;
    if (value > 9999) {//大于9999显示x.x万
      num = (Math.floor(value / 1000) / 10) + 'W';
    } else if (value < 9999 && value > -9999) {
      num = value
    } else if (value < -9999) {//小于-9999显示-x.x万
      num = -(Math.floor(Math.abs(value) / 1000) / 10) + 'W'
    }
    return num;
}
// 获取本周日期范围
const currentWeek = ()=>{
    var now = new Date();             //当前日期 
    var nowYear = now.getFullYear();  //当前年 
    var nowDate = now.getDate();      //当前日 
    var nowMonth = now.getMonth();    //当前月
    var nowDayOfWeek = now.getDay();  //今天本周的第几天 

    let weekStartDate = new Date(nowYear, nowMonth, nowDate - (nowDayOfWeek - 1)); 
    let weekEndDate = new Date(nowYear, nowMonth, nowDate + (7 - nowDayOfWeek)); 
    return `(${formatDate(weekStartDate)}-${formatDate(weekEndDate)})`;
}
//格式化日期：MM.dd 
const formatDate = (date)=>{ 
    var month = date.getMonth() + 1; 
    var date = date.getDate();
    return (month + "." + date);
}
// 获取数组里的最小值及索引
const getMin = (arr)=> {
    let minIndex = 0;
    let minValue = arr[0];
    arr.forEach((val,i)=>{
        if(minValue > val){
            minValue = val;
            minIndex = i;
        }
    })
    return {
        index:minIndex,
        value:minValue
    }
}
// 获取数组里的最大值及索引
const getMax = (arr) => {
    let maxIndex = 0;
    let maxValue = arr[0];
    arr.forEach((val,i)=>{
        if(maxValue < val){
            maxValue = val;
            maxIndex = i;
        }
    })
    return {
        index:maxIndex,
        value:maxValue
    }
}

export {
    addToken,
    getWechatCode,
    isPhoneNumber,
    millionNum,
    currentWeek,
    formatDate,
    getMin,
    getMax
}